package com.yeziji.config;

import cn.hutool.extra.spring.SpringUtil;
import com.yeziji.common.CommonSymbol;
import com.yeziji.utils.expansion.Str2;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * banner 控制台输出
 *
 * @author hwy
 * @since 2024/11/11 17:15
 **/
@Order
@Configuration
public class BannerConfig implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<String> banners = new ArrayList<>();
        banners.add("##########################################################################################");
        banners.add(CommonSymbol.EMPTY);
        banners.add(" \\ \\   / __  /      |       ___|    ___|     \\     ____|  ____|  _ \\   |      __ \\  ");
        banners.add("  \\   /     /       |     \\___ \\   |        _ \\    |      |     |   |  |      |   | ");
        banners.add("     |     /    \\   | _____|    |  |       ___ \\   __|    __|   |   |  |      |   | ");
        banners.add("    _|   ____| \\___/      _____/  \\____| _/    _\\ _|     _|    \\___/  _____| ____/  ");
        banners.add(CommonSymbol.EMPTY);
        Str2.notBlankThen(getBeanBanner("securityConfig"), banners::add);
        Str2.notBlankThen(getBeanBanner("autoDynamicConfig"), banners::add);
        Str2.notBlankThen(getBeanBanner("yzjJobConfig"), banners::add);
        Str2.notBlankThen(getBeanBanner("devopsConfig"), banners::add);
        banners.add("##########################################################################################");
        banners.forEach(System.out::println);
    }

    /**
     * 通过 SpringUtil 查找 bean 的注入情况，如果 catch 说明未注入
     *
     * @param beanName bean 名称
     * @return {@link String} 对应的输出字符
     */
    private static String getBeanBanner(String beanName) {
        try {
            Object bean = SpringUtil.getBean(beanName);
            if (bean != null) {
                return "running: " + getBeanName(beanName);
            }
        } catch (Exception e) {
            return "";
        }
        return "";
    }

    /**
     * 获取对应 bean 的组件名称
     *
     * @param beanName 组件名称
     * @return {@link String} 组件名称
     */
    private static String getBeanName(String beanName) {
        switch (beanName) {
            case "autoDynamicConfig":
                return "YZJ Config";
            case "yzjJobConfig":
                return "YZJ Job";
            case "devopsConfig":
                return "YZJ Devops";
            case "securityConfig":
                return "YZJ Security";
            default:
                return "";
        }
    }
}
